<template>
  <main class="table-container">
    <!-- 页面标题和操作按钮 -->
    <div class="header-section">
      <h1 class="page-title">
        <i class="fas fa-list-alt"></i>
        <div v-if="isEditingTitle" class="title-edit-container">
          <input
            v-model="editingTitleValue"
            @keyup.enter="saveTitleEdit"
            @keyup.escape="cancelTitleEdit"
            @blur="saveTitleEdit"
            class="title-edit-input"
            maxlength="20"
          />
          <div class="title-edit-actions">
            <button @click="saveTitleEdit" class="title-edit-btn save-btn">
              <i class="fas fa-check"></i>
            </button>
            <button @click="cancelTitleEdit" class="title-edit-btn cancel-btn">
              <i class="fas fa-times"></i>
            </button>
          </div>
        </div>
        <div v-else @click="startTitleEdit" class="editable-title" :title="'点击编辑系统名称: ' + systemTitle">
          {{ systemTitle }}
          <i class="fas fa-edit title-edit-icon"></i>
        </div>
      </h1>
      <div class="header-actions">
        <button @click="addNewDevice" class="action-btn device-btn">
          <i class="fas fa-cogs"></i>
          新增设备
        </button>
        <button @click="addNewPerson" class="action-btn person-btn">
          <i class="fas fa-user-plus"></i>
          新增责任人
        </button>
      </div>
    </div>



    <!-- 问题管理操作区域 -->
    <div class="issue-actions-section">
      <div class="issue-actions">
        <button @click="addNewIssue" class="action-btn issue-btn">
          <i class="fas fa-plus-circle"></i>
          新增问题
        </button>
        <button @click="exportIssues" class="action-btn export-issue-btn">
          <i class="fas fa-file-export"></i>
          导出问题
        </button>
      </div>
    </div>

    <!-- 数据表格 -->
    <div class="table-wrapper">
      <table class="data-table">
        <thead>
          <tr>
            <th class="col-number">问题点</th>
            <th class="col-datetime">提出时间</th>
            <th class="col-machine">设备编号</th>
            <th class="col-device">设备名称</th>
            <th class="col-description">问题描述</th>
            <th class="col-stage">项目阶段</th>
            <th class="col-solution">解决措施</th>
            <th class="col-department">责任单位</th>
            <th class="col-person">责任人</th>
            <th class="col-datetime">计划完成时间</th>
            <th class="col-datetime">实际完成时间</th>
            <th class="col-status">状态</th>
            <th class="col-remark">备注</th>
            <th class="col-actions">
              <i class="fas fa-cogs"></i>
              操作
            </th>
          </tr>
        </thead>
        <tbody>
          <tr v-if="isLoading">
            <td colspan="14" class="loading-row">
              <i class="fas fa-spinner fa-spin"></i>
              数据加载中...
            </td>
          </tr>
          <tr v-else-if="filteredData.length === 0">
            <td colspan="14" class="empty-row">
              <i class="fas fa-inbox"></i>
              暂无数据
            </td>
          </tr>
          <tr v-else v-for="(item, index) in paginatedData" :key="item.id" class="data-row">
            <td class="col-number">{{ getDisplayIndex(index) }}</td>
            <td class="col-datetime">{{ item.submitTime }}</td>
            <td class="col-machine">{{ item.machineNumber }}</td>
            <td class="col-device">{{ item.deviceName }}</td>
            <td class="col-description" :title="item.description">
              {{ truncateText(item.description, 30) }}
            </td>
            <td class="col-stage">{{ item.projectStage }}</td>
            <td class="col-solution" :title="item.solution">
              {{ truncateText(item.solution, 25) }}
            </td>
            <td class="col-department">{{ item.department }}</td>
            <td class="col-person">{{ item.responsiblePerson }}</td>
            <td class="col-datetime">{{ item.plannedCompletionTime }}</td>
            <td class="col-datetime">{{ item.actualCompletionTime || '-' }}</td>
            <td class="col-status">
              <span :class="getStatusClass(item.status)">{{ item.status }}</span>
            </td>
            <td class="col-remark" :title="item.remark">
              {{ truncateText(item.remark, 20) }}
            </td>
            <td class="col-actions">
              <div class="action-buttons">
                <button @click="editItem(item)" class="action-btn-small edit-btn">
                  <i class="fas fa-edit"></i>
                </button>
                <button @click="deleteItem(item)" class="action-btn-small delete-btn">
                  <i class="fas fa-trash"></i>
                </button>
              </div>
            </td>
          </tr>
        </tbody>
      </table>
    </div>

    <!-- 分页控件 -->
    <div class="pagination-section" v-if="filteredData.length > 0">
      <div class="pagination-info">
        共 {{ filteredData.length }} 条记录，当前第 {{ currentPage }} / {{ totalPages }} 页
      </div>
      <div class="pagination-controls">
        <button 
          @click="goToPage(1)" 
          :disabled="currentPage === 1"
          class="page-btn"
        >
          首页
        </button>
        <button 
          @click="goToPage(currentPage - 1)" 
          :disabled="currentPage === 1"
          class="page-btn"
        >
          上一页
        </button>
        <span class="page-numbers">
          <button 
            v-for="page in getPageNumbers()" 
            :key="page"
            @click="goToPage(page)"
            :class="['page-btn', { 'active': page === currentPage }]"
          >
            {{ page }}
          </button>
        </span>
        <button 
          @click="goToPage(currentPage + 1)" 
          :disabled="currentPage === totalPages"
          class="page-btn"
        >
          下一页
        </button>
        <button 
          @click="goToPage(totalPages)" 
          :disabled="currentPage === totalPages"
          class="page-btn"
        >
          末页
        </button>
      </div>
      <div class="page-size-selector">
        <label>每页显示:</label>
        <select v-model="pageSize" @change="handlePageSizeChange">
          <option value="10">10</option>
          <option value="20">20</option>
          <option value="50">50</option>
          <option value="100">100</option>
        </select>
        <span>条</span>
      </div>
    </div>
  </main>

  <!-- 新增设备弹窗 -->
  <div v-if="modals.addDevice" class="modal-overlay" @click="closeAddDeviceModal">
    <div class="modal-content add-modal batch-modal" @click.stop>
      <div class="modal-header">
        <h2 class="modal-title">
          <i class="fas fa-cogs"></i>
          批量新增设备
        </h2>
        <button @click="closeAddDeviceModal" class="close-button">
          <i class="fas fa-times"></i>
        </button>
      </div>
      
      <div class="modal-body">
        <!-- 已有设备列表 -->
        <div class="existing-devices-section">
          <div class="section-header" @click="toggleExistingDevices">
            <h3 class="section-title">
              <i class="fas fa-list"></i>
              已有设备 ({{ deviceList.length }} 台)
              <i :class="showStates.existingDevices ? 'fas fa-chevron-up' : 'fas fa-chevron-down'" class="toggle-icon"></i>
            </h3>
          </div>
          
          <div v-show="showStates.existingDevices" class="existing-devices-list">
            <div class="existing-devices-header">
              <span>设备编号</span>
              <span>设备名称</span>
              <span>创建时间</span>
              <span>操作</span>
            </div>
            <div class="existing-devices-body">
              <div v-if="deviceList.length === 0" class="no-devices">
                暂无设备数据
              </div>
              <div 
                v-else
                v-for="device in deviceList" 
                :key="device.id" 
                class="existing-device-row"
              >
                <span class="device-number">{{ device.machineNumber }}</span>
                <span class="device-name">{{ device.name }}</span>
                <span class="device-time">{{ device.createTime || '系统默认' }}</span>
                <span class="device-action">
                  <button 
                    @click="deleteDevice(device)" 
                    class="delete-btn"
                    title="删除此设备"
                  >
                    <i class="fas fa-trash"></i>
                  </button>
                </span>
              </div>
            </div>
          </div>
        </div>

        <!-- 批量新增表单 -->
        <div class="batch-form-container">
          <div class="batch-header">
            <div class="batch-header-item">设备编号 <span class="required">*</span></div>
            <div class="batch-header-item">设备名称 <span class="required">*</span></div>
            <div class="batch-header-action">操作</div>
          </div>
          
          <div class="batch-rows">
            <div 
              v-for="(device, index) in batchDevices" 
              :key="index" 
              class="batch-row"
            >
              <div class="batch-row-item">
                <input
                  type="text"
                  v-model="device.machineNumber"
                  class="batch-input"
                  :placeholder="getNextMachineNumberSuggestion(index)"
                />
              </div>
              <div class="batch-row-item">
                <input
                  type="text"
                  v-model="device.name"
                  class="batch-input"
                  placeholder="设备名称"
                />
              </div>
              <div class="batch-row-action">
                <button 
                  @click="removeDeviceRow(index)" 
                  class="batch-btn batch-btn-remove"
                  :disabled="batchDevices.length === 1"
                  title="删除此行"
                >
                  <i class="fas fa-trash"></i>
                </button>
              </div>
            </div>
          </div>
          
          <div class="batch-actions">
            <button @click="addDeviceRow" class="batch-btn batch-btn-add">
              <i class="fas fa-plus"></i>
              添加设备行
            </button>
          </div>
        </div>
      </div>
      
      <div class="modal-footer">
        <button @click="submitNewDevice" class="modal-btn modal-btn-primary">
          <i class="fas fa-save"></i>
          批量保存 ({{ batchDevices.filter(d => d.machineNumber.trim() || d.name.trim()).length }} 台)
        </button>
        <button @click="closeAddDeviceModal" class="modal-btn modal-btn-secondary">
          <i class="fas fa-times"></i>
          取消
        </button>
      </div>
    </div>
  </div>

  <!-- 新增责任人弹窗 -->
  <div v-if="modals.addPerson" class="modal-overlay" @click="closeAddPersonModal">
    <div class="modal-content add-modal batch-modal" @click.stop>
      <div class="modal-header">
        <h2 class="modal-title">
          <i class="fas fa-user-plus"></i>
          批量新增责任人
        </h2>
        <button @click="closeAddPersonModal" class="close-button">
          <i class="fas fa-times"></i>
        </button>
      </div>
      
      <div class="modal-body">
        <!-- 已有责任人列表 -->
        <div class="existing-devices-section">
          <div class="section-header" @click="toggleExistingPersons">
            <h3 class="section-title">
              <i class="fas fa-users"></i>
              已有责任人 ({{ personList.length }} 人)
              <i :class="showStates.existingPersons ? 'fas fa-chevron-up' : 'fas fa-chevron-down'" class="toggle-icon"></i>
            </h3>
          </div>
          
          <div v-show="showStates.existingPersons" class="existing-devices-list">
                         <div class="existing-devices-header">
               <span>姓名</span>
               <span>单位</span>
               <span>电话</span>
               <span>操作</span>
             </div>
            <div class="existing-devices-body">
              <div v-if="personList.length === 0" class="no-devices">
                暂无责任人数据
              </div>
                             <div 
                 v-else
                 v-for="person in personList" 
                 :key="person.id" 
                 class="existing-device-row"
               >
                 <span class="device-number">{{ person.name }}</span>
                 <span class="device-name">{{ person.department }}</span>
                 <span class="device-time">{{ person.phone }}</span>
                 <span class="device-action">
                   <button 
                     @click="deletePerson(person)" 
                     class="delete-btn"
                     title="删除此责任人"
                   >
                     <i class="fas fa-trash"></i>
                   </button>
                 </span>
               </div>
            </div>
          </div>
        </div>

        <!-- 批量新增表单 -->
        <div class="batch-form-container">
                     <div class="batch-header batch-header-person">
             <div class="batch-header-item">姓名 <span class="required">*</span></div>
             <div class="batch-header-item">单位 <span class="required">*</span></div>
             <div class="batch-header-item">电话 <span class="required">*</span></div>
             <div class="batch-header-action">操作</div>
           </div>
          
          <div class="batch-rows">
                         <div 
               v-for="(person, index) in batchPersons" 
               :key="index" 
               class="batch-row batch-row-person"
             >
              <div class="batch-row-item">
                <input
                  type="text"
                  v-model="person.name"
                  class="batch-input"
                  placeholder="如: 张三"
                />
              </div>
                             <div class="batch-row-item">
                 <input
                   type="text"
                   v-model="person.department"
                   class="batch-input"
                   placeholder="如: 凯昇"
                 />
               </div>
              <div class="batch-row-item">
                <input
                  type="tel"
                  v-model="person.phone"
                  class="batch-input"
                  placeholder="如: 13800138001"
                />
              </div>
              <div class="batch-row-action">
                <button 
                  @click="removePersonRow(index)" 
                  class="batch-btn batch-btn-remove"
                  :disabled="batchPersons.length === 1"
                  title="删除此行"
                >
                  <i class="fas fa-trash"></i>
                </button>
              </div>
            </div>
          </div>
          
          <div class="batch-actions">
            <button @click="addPersonRow" class="batch-btn batch-btn-add">
              <i class="fas fa-plus"></i>
              添加责任人行
            </button>
          </div>
        </div>
      </div>
      
      <div class="modal-footer">
        <button @click="submitNewPerson" class="modal-btn modal-btn-primary">
          <i class="fas fa-save"></i>
          批量保存 ({{ batchPersons.filter(p => p.name.trim() || p.department.trim() || p.phone.trim()).length }} 人)
        </button>
        <button @click="closeAddPersonModal" class="modal-btn modal-btn-secondary">
          <i class="fas fa-times"></i>
          取消
        </button>
      </div>
    </div>
  </div>

  <!-- 新增责任单位弹窗 -->
  <div v-if="modals.addDepartment" class="modal-overlay" @click="closeAddDepartmentModal">
    <div class="modal-content add-modal" @click.stop>
      <div class="modal-header">
        <h2 class="modal-title">
          <i class="fas fa-building"></i>
          新增责任单位
        </h2>
        <button @click="closeAddDepartmentModal" class="close-button">
          <i class="fas fa-times"></i>
        </button>
      </div>
      
      <div class="modal-body">
        <form @submit.prevent="submitNewDepartment">
          <div class="form-row">
            <div class="form-group">
              <label class="form-label">单位名称 <span class="required">*</span></label>
              <input
                type="text"
                v-model="newDepartmentForm.name"
                class="form-input"
                placeholder="如: 设备维护部"
                required
              />
            </div>
            <div class="form-group">
              <label class="form-label">负责人 <span class="required">*</span></label>
              <input
                type="text"
                v-model="newDepartmentForm.manager"
                class="form-input"
                placeholder="如: 张工程师"
                required
              />
            </div>
          </div>

          <div class="form-row">
            <div class="form-group">
              <label class="form-label">联系电话</label>
              <input
                type="tel"
                v-model="newDepartmentForm.phone"
                class="form-input"
                placeholder="如: 0755-88888001"
              />
            </div>
            <div class="form-group">
              <label class="form-label">办公地址</label>
              <input
                type="text"
                v-model="newDepartmentForm.address"
                class="form-input"
                placeholder="如: 二楼设备管理办公室"
              />
            </div>
          </div>

          <div class="form-group">
            <label class="form-label">部门职责</label>
            <textarea
              v-model="newDepartmentForm.description"
              class="form-textarea"
              placeholder="描述该部门的主要职责和工作范围..."
              rows="3"
            ></textarea>
          </div>
        </form>
      </div>
      
      <div class="modal-footer">
        <button @click="submitNewDepartment" class="modal-btn modal-btn-primary">
          <i class="fas fa-save"></i>
          保存单位
        </button>
        <button @click="closeAddDepartmentModal" class="modal-btn modal-btn-secondary">
          <i class="fas fa-times"></i>
          取消
        </button>
      </div>
    </div>
  </div>

  <!-- 编辑问题弹窗 -->
  <div v-if="modals.editIssue" class="modal-overlay" @click="closeEditIssueModal">
    <div class="modal-content add-modal issue-modal" @click.stop>
      <div class="modal-header">
        <h2 class="modal-title">
          <i class="fas fa-edit"></i>
          编辑问题点 {{ editIssueForm.id }}
        </h2>
        <button @click="closeEditIssueModal" class="close-button">
          <i class="fas fa-times"></i>
        </button>
      </div>
      
      <div class="modal-body">
        <form @submit.prevent="submitEditIssue">
          <div class="form-row">
            <div class="form-group">
              <label class="form-label">提出时间</label>
              <input
                type="text"
                v-model="editIssueForm.submitTime"
                class="form-input"
                readonly
                style="background-color: #f0f0f0;"
              />
            </div>
            <div class="form-group">
              <label class="form-label">设备 <span class="required">*</span></label>
              <select v-model="editIssueForm.deviceId" class="form-input" required>
                <option value="">请选择设备</option>
                <option v-for="device in deviceList" :key="device.id" :value="device.id">
                  {{ device.machineNumber }} - {{ device.name }}
                </option>
              </select>
            </div>
          </div>

          <div class="form-group">
            <label class="form-label">问题描述 <span class="required">*</span></label>
            <textarea
              v-model="editIssueForm.description"
              class="form-textarea"
              placeholder="请详细描述遇到的问题..."
              rows="4"
              required
            ></textarea>
          </div>

          <div class="form-row">
            <div class="form-group">
              <label class="form-label">项目阶段 <span class="required">*</span></label>
              <select v-model="editIssueForm.projectStage" class="form-input" required>
                <option value="">请选择项目阶段</option>
                <option value="单机调试">单机调试</option>
                <option value="连机调试">连机调试</option>
              </select>
            </div>
            <div class="form-group">
              <label class="form-label">责任单位 <span class="required">*</span></label>
              <select v-model="editIssueForm.responsibleDepartment" class="form-input" required>
                <option value="">请选择责任单位</option>
                <option v-for="dept in uniqueDepartments" :key="dept" :value="dept">
                  {{ dept }}
                </option>
              </select>
            </div>
          </div>

          <div class="form-group">
            <label class="form-label">解决措施</label>
            <textarea
              v-model="editIssueForm.solution"
              class="form-textarea"
              placeholder="请输入解决措施或解决方案..."
              rows="3"
            ></textarea>
          </div>

          <div class="form-row">
            <div class="form-group">
              <label class="form-label">责任人</label>
              <select v-model="editIssueForm.responsiblePersonId" class="form-input">
                <option value="">请选择责任人</option>
                <option v-for="person in filteredPersonsForEdit" :key="person.id" :value="person.id">
                  {{ person.name }} ({{ person.department }})
                </option>
              </select>
            </div>
            <div class="form-group">
              <label class="form-label">计划完成时间</label>
              <input
                type="datetime-local"
                v-model="editIssueForm.plannedCompletionTime"
                class="form-input"
              />
            </div>
          </div>

          <div class="form-row">
            <div class="form-group">
              <label class="form-label">状态</label>
              <select v-model="editIssueForm.status" class="form-input" @change="handleEditStatusChange">
                <option value="处理中">处理中</option>
                <option value="已完成">已完成</option>
              </select>
            </div>
            <div class="form-group" v-if="editIssueForm.actualCompletionTime">
              <label class="form-label">实际完成时间</label>
              <input
                type="text"
                v-model="editIssueForm.actualCompletionTime"
                class="form-input"
                readonly
                style="background-color: #f0f0f0;"
              />
            </div>
          </div>

          <div class="form-group">
            <label class="form-label">备注</label>
            <textarea
              v-model="editIssueForm.remark"
              class="form-textarea"
              placeholder="请输入相关备注信息..."
              rows="3"
            ></textarea>
          </div>
        </form>
      </div>
      
      <div class="modal-footer">
        <button @click="submitEditIssue" class="modal-btn modal-btn-primary">
          <i class="fas fa-save"></i>
          保存修改
        </button>
        <button @click="closeEditIssueModal" class="modal-btn modal-btn-secondary">
          <i class="fas fa-times"></i>
          取消
        </button>
      </div>
    </div>
  </div>

  <!-- 通知组件 -->
  <div
    id="notification"
    class="notification-dialog"
    :class="{ show: notification.visible, 'notification-success': notification.type === 'success', 'notification-error': notification.type === 'error' }"
    v-show="notification.visible"
  >
    <div class="notification-content">
      <i :class="notification.type === 'success' ? 'fas fa-check-circle' : 'fas fa-exclamation-circle'"
         class="notification-icon"></i>
      <span>{{ notification.message }}</span>
    </div>
  </div>

  <!-- 新增问题弹窗 -->
  <div v-if="modals.addIssue" class="modal-overlay" @click="closeAddIssueModal">
    <div class="modal-content add-modal issue-modal" @click.stop>
      <div class="modal-header">
        <h2 class="modal-title">
          <i class="fas fa-plus-circle"></i>
          新增问题
        </h2>
        <button @click="closeAddIssueModal" class="close-button">
          <i class="fas fa-times"></i>
        </button>
      </div>
      
             <div class="modal-body">
         <form @submit.prevent="submitNewIssue">
           <div class="form-row">
             <div class="form-group">
               <label class="form-label">提出时间</label>
               <input
                 type="text"
                 v-model="newIssueForm.submitTime"
                 class="form-input"
                 readonly
                 style="background-color: #f0f0f0;"
               />
             </div>
             <div class="form-group">
               <label class="form-label">设备 <span class="required">*</span></label>
               <select v-model="newIssueForm.deviceId" class="form-input" required>
                 <option value="">请选择设备</option>
                 <option v-for="device in deviceList" :key="device.id" :value="device.id">
                   {{ device.machineNumber }} - {{ device.name }}
                 </option>
               </select>
             </div>
           </div>

           <div class="form-group">
             <label class="form-label">问题描述 <span class="required">*</span></label>
             <textarea
               v-model="newIssueForm.description"
               class="form-textarea"
               placeholder="请详细描述遇到的问题..."
               rows="4"
               required
             ></textarea>
           </div>

           <div class="form-row">
             <div class="form-group">
               <label class="form-label">项目阶段 <span class="required">*</span></label>
               <select v-model="newIssueForm.projectStage" class="form-input" required>
                 <option value="">请选择项目阶段</option>
                 <option value="单机调试">单机调试</option>
                 <option value="连机调试">连机调试</option>
               </select>
             </div>
             <div class="form-group">
               <label class="form-label">责任单位 <span class="required">*</span></label>
               <select v-model="newIssueForm.responsibleDepartment" class="form-input" required>
                 <option value="">请选择责任单位</option>
                 <option v-for="dept in uniqueDepartments" :key="dept" :value="dept">
                   {{ dept }}
                 </option>
               </select>
             </div>
           </div>

           <div class="form-group">
             <label class="form-label">解决措施</label>
             <textarea
               v-model="newIssueForm.solution"
               class="form-textarea"
               placeholder="请输入解决措施或解决方案..."
               rows="3"
             ></textarea>
           </div>

           <div class="form-row">
             <div class="form-group">
               <label class="form-label">责任人</label>
               <select v-model="newIssueForm.responsiblePersonId" class="form-input">
                 <option value="">请选择责任人</option>
                 <option v-for="person in filteredPersons" :key="person.id" :value="person.id">
                   {{ person.name }} ({{ person.department }})
                 </option>
               </select>
             </div>
             <div class="form-group">
               <label class="form-label">计划完成时间</label>
               <input
                 type="datetime-local"
                 v-model="newIssueForm.plannedCompletionTime"
                 class="form-input"
               />
             </div>
           </div>

           <div class="form-row">
             <div class="form-group">
               <label class="form-label">状态</label>
               <select v-model="newIssueForm.status" class="form-input" @change="handleStatusChange">
                 <option value="处理中">处理中</option>
                 <option value="已完成">已完成</option>
               </select>
             </div>
             <div class="form-group" v-if="newIssueForm.actualCompletionTime">
               <label class="form-label">实际完成时间</label>
               <input
                 type="text"
                 v-model="newIssueForm.actualCompletionTime"
                 class="form-input"
                 readonly
                 style="background-color: #f0f0f0;"
               />
             </div>
           </div>

           <div class="form-group">
             <label class="form-label">备注</label>
             <textarea
               v-model="newIssueForm.remark"
               class="form-textarea"
               placeholder="请输入相关备注信息..."
               rows="3"
             ></textarea>
           </div>
         </form>
       </div>
       
       <div class="modal-footer">
         <button @click="submitNewIssue" class="modal-btn modal-btn-primary">
           <i class="fas fa-save"></i>
           确定新增
         </button>
         <button @click="closeAddIssueModal" class="modal-btn modal-btn-secondary">
           <i class="fas fa-times"></i>
           取消
         </button>
       </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch } from 'vue';

// ==================== 响应式数据 ====================
const isLoading = ref(false);
const currentPage = ref(1);
const pageSize = ref(20);

// 标题编辑相关
const systemTitle = ref('设备管理系统');
const isEditingTitle = ref(false);
const editingTitleValue = ref('');

// 通知状态
const notification = reactive({
  visible: false,
  message: '',
  type: 'success'
});

// 弹窗状态管理
const modals = reactive({
  addDevice: false,
  addPerson: false,
  addDepartment: false,
  addIssue: false,
  editIssue: false
});

const showStates = reactive({
  existingDevices: true,
  existingPersons: true
});

const editingIssue = ref(null);

// 数据管理
const deviceList = ref([
  { id: 1, name: '预装区(激光打铭牌)', machineNumber: 'XHD01-01' },
  { id: 2, name: 'AOI检测设备', machineNumber: 'XHD02-03' },
  { id: 3, name: '自动焊接机', machineNumber: 'XHD03-05' },
  { id: 4, name: '包装封口机', machineNumber: 'XHD04-02' },
  { id: 5, name: '视觉检测系统', machineNumber: 'XHD05-01' }
]);

const personList = ref([
  { id: 1, name: '张工程师', department: '设备部', phone: '13800138001', email: 'zhang@company.com' },
  { id: 2, name: '李工程师', department: '技术部', phone: '13800138002', email: 'li@company.com' },
  { id: 3, name: '王主管', department: '生产部', phone: '13800138003', email: 'wang@company.com' },
  { id: 4, name: '陈检验员', department: '质量部', phone: '13800138004', email: 'chen@company.com' },
  { id: 5, name: '赵技术员', department: '设备部', phone: '13800138005', email: 'zhao@company.com' }
]);

const departmentList = ref([
  { id: 1, name: '设备部', manager: '张工程师', phone: '0755-88888001', description: '负责设备维护和管理' },
  { id: 2, name: '技术部', manager: '李工程师', phone: '0755-88888002', description: '负责技术支持和算法优化' },
  { id: 3, name: '生产部', manager: '王主管', phone: '0755-88888003', description: '负责生产计划和执行' },
  { id: 4, name: '质量部', manager: '陈检验员', phone: '0755-88888004', description: '负责质量检测和控制' }
]);

// 批量表单数据
const batchDevices = ref([{ machineNumber: '', name: '' }]);
const batchPersons = ref([{ name: '', department: '', phone: '' }]);

// 单项表单数据
const newDepartmentForm = reactive({
  name: '', manager: '', phone: '', description: '', address: ''
});

const newIssueForm = reactive({
  submitTime: '', deviceId: '', description: '', projectStage: '', solution: '',
  responsibleDepartment: '', responsiblePersonId: '', plannedCompletionTime: '',
  actualCompletionTime: '', status: '处理中', remark: ''
});

const editIssueForm = reactive({
  id: '', submitTime: '', deviceId: '', description: '', projectStage: '', solution: '',
  responsibleDepartment: '', responsiblePersonId: '', plannedCompletionTime: '',
  actualCompletionTime: '', status: '', remark: ''
});

// 问题数据
const tableData = ref([
  {
    id: 1, submitTime: '2025-01-15 09:30:00', machineNumber: 'XHD01-01',
    deviceName: '预装区(激光打铭牌)', description: '激光打标设备功率不稳定，导致打标深度不一致，影响产品质量',
    projectStage: '批量生产', solution: '更换激光器模块，调整功率参数设置', department: '设备部',
    responsiblePerson: '张工程师', plannedCompletionTime: '2025-01-20 18:00:00', actualCompletionTime: '',
    status: '处理中', remark: '已联系供应商，备件预计明日到货'
  },
  {
    id: 2, submitTime: '2025-01-14 14:15:00', machineNumber: 'XHD02-03',
    deviceName: 'AOI检测设备', description: 'AOI检测误判率较高，正常产品被误判为不良品',
    projectStage: '试产阶段', solution: '重新校准检测参数，更新检测算法', department: '技术部',
    responsiblePerson: '李工程师', plannedCompletionTime: '2025-01-18 16:00:00', actualCompletionTime: '2025-01-17 15:30:00',
    status: '已完成', remark: '参数调整完成，误判率降至1%以下'
  },
  {
    id: 3, submitTime: '2025-01-13 11:20:00', machineNumber: 'XHD03-05',
    deviceName: '自动焊接机', description: '焊接温度控制异常，焊点质量不稳定',
    projectStage: '量产阶段', solution: '更换温控传感器，重新标定温度曲线', department: '生产部',
    responsiblePerson: '王主管', plannedCompletionTime: '2025-01-22 17:00:00', actualCompletionTime: '',
    status: '待处理', remark: '等待传感器到货'
  },
  {
    id: 4, submitTime: '2025-01-12 16:45:00', machineNumber: 'XHD04-02',
    deviceName: '包装封口机', description: '封口强度不足，包装袋存在漏气现象',
    projectStage: '批量生产', solution: '调整封口温度和压力参数，更换封口带', department: '质量部',
    responsiblePerson: '陈检验员', plannedCompletionTime: '2025-01-19 12:00:00', actualCompletionTime: '',
    status: '处理中', remark: '已调整参数，待验证效果'
  },
  {
    id: 5, submitTime: '2025-01-11 10:30:00', machineNumber: 'XHD05-01',
    deviceName: '视觉检测系统', description: '相机镜头有污渍，影响检测精度',
    projectStage: '试产阶段', solution: '清洁镜头，安装防护罩防止污染', department: '设备部',
    responsiblePerson: '赵技术员', plannedCompletionTime: '2025-01-15 14:00:00', actualCompletionTime: '2025-01-15 13:20:00',
    status: '已完成', remark: '清洁完成，检测精度恢复正常'
  }
]);

// ==================== 计算属性 ====================
const filteredData = computed(() => tableData.value);
const totalPages = computed(() => Math.ceil(filteredData.value.length / pageSize.value));
const paginatedData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  return filteredData.value.slice(start, start + pageSize.value);
});

const uniqueDepartments = computed(() => {
  const departments = personList.value.map(person => person.department);
  return [...new Set(departments)].filter(dept => dept && dept.trim());
});

const filteredPersons = computed(() => {
  if (!newIssueForm.responsibleDepartment) return personList.value;
  return personList.value.filter(person => person.department === newIssueForm.responsibleDepartment);
});

const filteredPersonsForEdit = computed(() => {
  if (!editIssueForm.responsibleDepartment) return personList.value;
  return personList.value.filter(person => person.department === editIssueForm.responsibleDepartment);
});

// ==================== 工具函数 ====================
const showNotification = (message, type = 'success') => {
  notification.message = message;
  notification.type = type;
  notification.visible = true;
  setTimeout(() => notification.visible = false, 3000);
};

const truncateText = (text, maxLength) => {
  if (!text) return '';
  return text.length > maxLength ? text.substring(0, maxLength) + '...' : text;
};

const getStatusClass = (status) => {
  const statusClasses = {
    '待处理': 'status-pending', '处理中': 'status-processing',
    '已完成': 'status-completed', '已关闭': 'status-closed'
  };
  return statusClasses[status] || 'status-default';
};

const formatCurrentTime = () => {
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, '0');
  const day = String(now.getDate()).padStart(2, '0');
  const hours = String(now.getHours()).padStart(2, '0');
  const minutes = String(now.getMinutes()).padStart(2, '0');
  const seconds = String(now.getSeconds()).padStart(2, '0');
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};

const formatDateTimeForDisplay = (datetimeLocalValue) => {
  if (!datetimeLocalValue) return '';
  const date = new Date(datetimeLocalValue);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  return `${year}-${month}-${day} ${hours}:${minutes}:00`;
};

const getDisplayIndex = (paginatedIndex) => {
  return (currentPage.value - 1) * pageSize.value + paginatedIndex + 1;
};

const getDefaultPlannedTime = () => {
  const tomorrow = new Date();
  tomorrow.setDate(tomorrow.getDate() + 1);
  const year = tomorrow.getFullYear();
  const month = String(tomorrow.getMonth() + 1).padStart(2, '0');
  const day = String(tomorrow.getDate()).padStart(2, '0');
  const hours = String(tomorrow.getHours()).padStart(2, '0');
  const minutes = String(tomorrow.getMinutes()).padStart(2, '0');
  return `${year}-${month}-${day}T${hours}:${minutes}`;
};

// ==================== 通用工具函数 ====================
// 通用ID生成器
const getNextId = (list) => {
  if (list.length === 0) return 1;
  return Math.max(...list.map(item => item.id)) + 1;
};

// 通用本地存储操作
const localStorageManager = {
  save: (key, data) => {
    try {
      localStorage.setItem(key, JSON.stringify(data));
      console.log(`${key} 数据已保存到本地存储`);
      return true;
    } catch (error) {
      console.error(`保存 ${key} 到本地存储失败:`, error);
      showNotification('保存到本地存储失败', 'error');
      return false;
    }
  },
  
  load: (key, defaultValue = []) => {
    try {
      const data = localStorage.getItem(key);
      return data ? JSON.parse(data) : defaultValue;
    } catch (error) {
      console.error(`读取本地 ${key} 数据失败:`, error);
      return defaultValue;
    }
  },
  
  saveBatch: (key, newItems, existingItems) => {
    try {
      const existing = localStorageManager.load(key, []);
      const all = [...existing, ...newItems];
      return localStorageManager.save(key, all);
    } catch (error) {
      console.error(`批量保存 ${key} 失败:`, error);
      return false;
    }
  },
  
  updateFiltered: (key, list, filterFn) => {
    try {
      const filtered = list.filter(filterFn);
      return localStorageManager.save(key, filtered);
    } catch (error) {
      console.error(`更新 ${key} 失败:`, error);
      return false;
    }
  }
};

// 通用数据库操作
const databaseManager = {
  buildData: (issues) => ({
    lastUpdated: formatCurrentTime(),
    totalCount: issues.length,
    version: '1.0',
    description: '问题管理系统数据库文件',
    issues
  }),
  
  save: async (issues) => {
    try {
      const databaseData = databaseManager.buildData(issues);
      localStorageManager.save('issuesDatabase', databaseData);
      localStorageManager.save('issuesData', { lastUpdated: formatCurrentTime(), totalCount: issues.length, issues });
      localStorageManager.save('issuesDatabaseBackup', databaseData);
      console.log(`数据库已更新，当前共 ${issues.length} 条记录`);
      return true;
    } catch (error) {
      console.error('更新数据库失败:', error);
      return false;
    }
  },
  
  load: async () => {
    try {
      const databaseData = localStorageManager.load('issuesDatabase', null);
      return databaseData ? databaseData.issues || [] : [];
    } catch (error) {
      console.error('读取数据库失败:', error);
      return [];
    }
  }
};

// 弹窗管理器
const modalManager = {
  open: (modalName) => {
    modals[modalName] = true;
  },
  
  close: (modalName) => {
    modals[modalName] = false;
  },
  
  toggle: (stateName) => {
    showStates[stateName] = !showStates[stateName];
  }
};

// ==================== 表单验证 ====================
const validators = {
  required: (value, fieldName) => {
    if (!value || !value.toString().trim()) {
      showNotification(`请输入${fieldName}`, 'error');
      return false;
    }
    return true;
  },
  
  batchValidation: (items, rules) => {
    for (let i = 0; i < items.length; i++) {
      const item = items[i];
      
      // 跳过空行
      if (Object.values(item).every(val => !val.toString().trim())) continue;
      
      for (const [field, fieldName] of Object.entries(rules)) {
        if (!validators.required(item[field], `第${i + 1}行：${fieldName}`)) {
          return { valid: false, validItems: [] };
        }
      }
    }
    
    const validItems = items.filter(item => 
      Object.values(item).some(val => val.toString().trim())
    );
    
    if (validItems.length === 0) {
      showNotification('请至少添加一条数据', 'error');
      return { valid: false, validItems: [] };
    }
    
    return { valid: true, validItems };
  },
  
  checkDuplicates: (items, existingList, keyField, itemName) => {
    const existingKeys = existingList.map(item => item[keyField]);
    
    for (let i = 0; i < items.length; i++) {
      const key = items[i][keyField].trim();
      const isDuplicate = existingKeys.includes(key) || 
        items.slice(0, i).some(item => item[keyField].trim() === key);
      
      if (isDuplicate) {
        showNotification(`第${i + 1}行：${itemName} ${key} 已存在`, 'error');
        return false;
      }
      existingKeys.push(key);
    }
    return true;
  }
};

// ==================== 业务逻辑函数 ====================
// 表单重置
const resetForms = {
  device: () => { batchDevices.value = [{ machineNumber: '', name: '' }]; },
  person: () => { batchPersons.value = [{ name: '', department: '', phone: '' }]; },
  department: () => { Object.keys(newDepartmentForm).forEach(key => newDepartmentForm[key] = ''); },
  issue: () => {
    newIssueForm.submitTime = formatCurrentTime();
    newIssueForm.deviceId = '';
    newIssueForm.description = '';
    newIssueForm.projectStage = '';
    newIssueForm.solution = '';
    newIssueForm.responsibleDepartment = '';
    newIssueForm.responsiblePersonId = '';
    newIssueForm.plannedCompletionTime = getDefaultPlannedTime();
    newIssueForm.actualCompletionTime = '';
    newIssueForm.status = '处理中';
    newIssueForm.remark = '';
  },
  editIssue: () => {
    Object.keys(editIssueForm).forEach(key => editIssueForm[key] = '');
    editingIssue.value = null;
  }
};

// 动态行管理
const rowManager = {
  add: (list, template) => { list.push({ ...template }); },
  remove: (list, index) => { if (list.length > 1) list.splice(index, 1); }
};

// 智能设备编号生成
const getNextMachineNumberSuggestion = (index) => {
  const existingNumbers = deviceList.value.map(d => d.machineNumber);
  let maxNumber = 0;
  const pattern = /XHD(\d+)-(\d+)/;
  
  existingNumbers.forEach(number => {
    const match = number.match(pattern);
    if (match) {
      const firstPart = parseInt(match[1]);
      const secondPart = parseInt(match[2]);
      const combined = firstPart * 100 + secondPart;
      maxNumber = Math.max(maxNumber, combined);
    }
  });
  
  if (maxNumber === 0) {
    return `XHD${String(index + 1).padStart(2, '0')}-01`;
  } else {
    const nextNumber = maxNumber + 1 + index;
    const firstPart = Math.floor(nextNumber / 100) || Math.floor(maxNumber / 100) + 1 + index;
    const secondPart = nextNumber % 100 || 1;
    return `XHD${String(firstPart).padStart(2, '0')}-${String(secondPart).padStart(2, '0')}`;
  }
};

// ==================== 主要业务函数 ====================
// 弹窗操作
const addNewDevice = () => {
  resetForms.device();
  showStates.existingDevices = true;
  modalManager.open('addDevice');
};

const addNewPerson = () => {
  resetForms.person();
  showStates.existingPersons = true;
  modalManager.open('addPerson');
};

const addNewDepartment = () => {
  resetForms.department();
  modalManager.open('addDepartment');
};

const addNewIssue = () => {
  resetForms.issue();
  modalManager.open('addIssue');
};

const closeAddDeviceModal = () => {
  modalManager.close('addDevice');
  resetForms.device();
};

const closeAddPersonModal = () => {
  modalManager.close('addPerson');
  resetForms.person();
};

const closeAddDepartmentModal = () => {
  modalManager.close('addDepartment');
  resetForms.department();
};

const closeAddIssueModal = () => {
  modalManager.close('addIssue');
  resetForms.issue();
};

const closeEditIssueModal = () => {
  modalManager.close('editIssue');
  resetForms.editIssue();
};

const toggleExistingDevices = () => modalManager.toggle('existingDevices');
const toggleExistingPersons = () => modalManager.toggle('existingPersons');

// 动态行操作
const addDeviceRow = () => rowManager.add(batchDevices.value, { machineNumber: '', name: '' });
const removeDeviceRow = (index) => rowManager.remove(batchDevices.value, index);
const addPersonRow = () => rowManager.add(batchPersons.value, { name: '', department: '', phone: '' });
const removePersonRow = (index) => rowManager.remove(batchPersons.value, index);

// 提交操作
const submitNewDevice = () => {
  const rules = { machineNumber: '设备编号', name: '设备名称' };
  const { valid, validItems } = validators.batchValidation(batchDevices.value, rules);
  if (!valid) return;
  
  if (!validators.checkDuplicates(validItems, deviceList.value, 'machineNumber', '设备编号')) return;
  
  const newDevices = validItems.map((device, index) => ({
    id: getNextId(deviceList.value) + index,
    machineNumber: device.machineNumber.trim(),
    name: device.name.trim(),
    createTime: formatCurrentTime()
  }));
  
  deviceList.value.unshift(...newDevices);
  localStorageManager.saveBatch('deviceList', newDevices, deviceList.value);
  
  closeAddDeviceModal();
  showNotification(`成功新增 ${newDevices.length} 台设备并保存到本地`, 'success');
};

const submitNewPerson = () => {
  const rules = { name: '责任人姓名', department: '单位名称', phone: '联系电话' };
  const { valid, validItems } = validators.batchValidation(batchPersons.value, rules);
  if (!valid) return;
  
  if (!validators.checkDuplicates(validItems, personList.value, 'name', '责任人')) return;
  
  const newPersons = validItems.map((person, index) => ({
    id: getNextId(personList.value) + index,
    name: person.name.trim(),
    department: person.department.trim(),
    phone: person.phone.trim(),
    createTime: formatCurrentTime()
  }));
  
  personList.value.unshift(...newPersons);
  localStorageManager.saveBatch('personList', newPersons, personList.value);
  
  closeAddPersonModal();
  showNotification(`成功新增 ${newPersons.length} 个责任人并保存到本地`, 'success');
};

const submitNewDepartment = () => {
  if (!validators.required(newDepartmentForm.name, '单位名称') || 
      !validators.required(newDepartmentForm.manager, '负责人')) return;
  
  const newDepartment = {
    id: getNextId(departmentList.value),
    name: newDepartmentForm.name.trim(),
    manager: newDepartmentForm.manager.trim(),
    phone: newDepartmentForm.phone.trim(),
    description: newDepartmentForm.description.trim(),
    address: newDepartmentForm.address.trim()
  };
  
  departmentList.value.unshift(newDepartment);
  closeAddDepartmentModal();
  showNotification(`成功新增责任单位: ${newDepartment.name}`, 'success');
};

const submitNewIssue = async () => {
  if (!validators.required(newIssueForm.deviceId, '设备') ||
      !validators.required(newIssueForm.description, '问题描述') ||
      !validators.required(newIssueForm.projectStage, '项目阶段') ||
      !validators.required(newIssueForm.responsibleDepartment, '责任单位')) return;
  
  const selectedDevice = deviceList.value.find(d => d.id === parseInt(newIssueForm.deviceId));
  if (!selectedDevice) {
    showNotification('所选设备不存在', 'error');
    return;
  }
  
  let responsiblePersonName = '待分配';
  if (newIssueForm.responsiblePersonId) {
    const selectedPerson = personList.value.find(p => p.id === parseInt(newIssueForm.responsiblePersonId));
    if (selectedPerson) responsiblePersonName = selectedPerson.name;
  }
  
  const newIssue = {
    id: getNextId(tableData.value),
    submitTime: newIssueForm.submitTime,
    machineNumber: selectedDevice.machineNumber,
    deviceName: selectedDevice.name,
    description: newIssueForm.description.trim(),
    projectStage: newIssueForm.projectStage,
    solution: newIssueForm.solution.trim() || '待制定',
    department: newIssueForm.responsibleDepartment,
    responsiblePerson: responsiblePersonName,
    plannedCompletionTime: newIssueForm.plannedCompletionTime ? formatDateTimeForDisplay(newIssueForm.plannedCompletionTime) : '',
    actualCompletionTime: newIssueForm.actualCompletionTime || '',
    status: newIssueForm.status,
    remark: newIssueForm.remark.trim()
  };
  
  tableData.value.unshift(newIssue);
  const success = await databaseManager.save(tableData.value);
  
  closeAddIssueModal();
  showNotification(`成功新增问题点 ${newIssue.id} 并保存到数据库`, 'success');
};

const submitEditIssue = async () => {
  if (!validators.required(editIssueForm.deviceId, '设备') ||
      !validators.required(editIssueForm.description, '问题描述') ||
      !validators.required(editIssueForm.projectStage, '项目阶段') ||
      !validators.required(editIssueForm.responsibleDepartment, '责任单位')) return;
  
  try {
    const selectedDevice = deviceList.value.find(d => d.id === parseInt(editIssueForm.deviceId));
    if (!selectedDevice) {
      showNotification('所选设备不存在', 'error');
      return;
    }
    
    let responsiblePersonName = '待分配';
    if (editIssueForm.responsiblePersonId) {
      const selectedPerson = personList.value.find(p => p.id === parseInt(editIssueForm.responsiblePersonId));
      if (selectedPerson) responsiblePersonName = selectedPerson.name;
    }
    
    const updatedIssue = {
      id: editIssueForm.id,
      submitTime: editIssueForm.submitTime,
      machineNumber: selectedDevice.machineNumber,
      deviceName: selectedDevice.name,
      description: editIssueForm.description.trim(),
      projectStage: editIssueForm.projectStage,
      solution: editIssueForm.solution.trim() || '待制定',
      department: editIssueForm.responsibleDepartment,
      responsiblePerson: responsiblePersonName,
      plannedCompletionTime: editIssueForm.plannedCompletionTime ? formatDateTimeForDisplay(editIssueForm.plannedCompletionTime) : '',
      actualCompletionTime: editIssueForm.actualCompletionTime || '',
      status: editIssueForm.status,
      remark: editIssueForm.remark.trim()
    };
    
    const index = tableData.value.findIndex(item => item.id === editIssueForm.id);
    if (index > -1) tableData.value[index] = updatedIssue;
    
    const success = await databaseManager.save(tableData.value);
    if (success) {
      closeEditIssueModal();
      showNotification(`问题点 ${editIssueForm.id} 修改成功并保存到数据库`, 'success');
    }
  } catch (error) {
    console.error('编辑问题失败:', error);
    showNotification('编辑问题失败', 'error');
  }
};

// 状态变化处理
const handleStatusChange = () => {
  if (newIssueForm.status === '已完成' && !newIssueForm.actualCompletionTime) {
    newIssueForm.actualCompletionTime = formatCurrentTime();
  } else if (newIssueForm.status === '处理中') {
    newIssueForm.actualCompletionTime = '';
  }
};

const handleEditStatusChange = () => {
  if (editIssueForm.status === '已完成' && !editIssueForm.actualCompletionTime) {
    editIssueForm.actualCompletionTime = formatCurrentTime();
  } else if (editIssueForm.status === '处理中') {
    editIssueForm.actualCompletionTime = '';
  }
};

// 删除操作
const deleteDevice = (device) => {
  if (confirm(`确定要删除设备 "${device.name}" (${device.machineNumber}) 吗？\n此操作不可恢复！`)) {
    const index = deviceList.value.findIndex(d => d.id === device.id);
    if (index > -1) deviceList.value.splice(index, 1);
    
    localStorageManager.updateFiltered('deviceList', deviceList.value, device => device.createTime);
    showNotification(`成功删除设备: ${device.name}`, 'success');
  }
};

const deletePerson = (person) => {
  if (confirm(`确定要删除责任人 "${person.name}" (${person.department}) 吗？\n此操作不可恢复！`)) {
    const index = personList.value.findIndex(p => p.id === person.id);
    if (index > -1) personList.value.splice(index, 1);
    
    localStorageManager.updateFiltered('personList', personList.value, person => person.createTime);
    showNotification(`成功删除责任人: ${person.name}`, 'success');
  }
};

// 编辑问题
const editItem = (item) => {
  editingIssue.value = item;
  
  // 预填充数据
  Object.assign(editIssueForm, {
    id: item.id,
    submitTime: item.submitTime,
    description: item.description,
    projectStage: item.projectStage,
    solution: item.solution || '',
    responsibleDepartment: item.department,
    status: item.status,
    remark: item.remark || '',
    actualCompletionTime: item.actualCompletionTime || ''
  });
  
  // 设备和责任人ID映射
  const device = deviceList.value.find(d => d.machineNumber === item.machineNumber);
  editIssueForm.deviceId = device ? device.id : '';
  
  const person = personList.value.find(p => p.name === item.responsiblePerson);
  editIssueForm.responsiblePersonId = person ? person.id : '';
  
  // 时间格式转换
  if (item.plannedCompletionTime) {
    editIssueForm.plannedCompletionTime = item.plannedCompletionTime.replace(' ', 'T').slice(0, 16);
  } else {
    editIssueForm.plannedCompletionTime = '';
  }
  
  modalManager.open('editIssue');
};

// 删除问题
const deleteItem = async (item) => {
  if (confirm(`确定要删除问题点 ${item.id} 吗？\n此操作不可恢复！`)) {
    try {
      const index = tableData.value.findIndex(data => data.id === item.id);
      if (index > -1) tableData.value.splice(index, 1);
      
      const success = await databaseManager.save(tableData.value);
      if (success) showNotification(`问题点 ${item.id} 删除成功`, 'success');
    } catch (error) {
      console.error('删除问题失败:', error);
      showNotification('删除问题失败', 'error');
    }
  }
};

// 导出问题数据
const exportIssues = async () => {
  try {
    const issues = await databaseManager.load();
    
    if (issues.length === 0) {
      showNotification('没有问题数据可导出', 'error');
      return;
    }
    
    const headers = ['问题点', '提出时间', '设备编号', '设备名称', '问题描述', '项目阶段', '解决措施', '责任单位', '责任人', '计划完成时间', '实际完成时间', '状态', '备注'];
    const csvData = [headers.join(',')];
    
    issues.forEach((issue, index) => {
      const row = [
        issue.id || (index + 1),
        `"${issue.submitTime || ''}"`,
        `"${issue.machineNumber || ''}"`,
        `"${issue.deviceName || ''}"`,
        `"${(issue.description || '').replace(/"/g, '""')}"`,
        `"${issue.projectStage || ''}"`,
        `"${(issue.solution || '').replace(/"/g, '""')}"`,
        `"${issue.department || ''}"`,
        `"${issue.responsiblePerson || ''}"`,
        `"${issue.plannedCompletionTime || ''}"`,
        `"${issue.actualCompletionTime || ''}"`,
        `"${issue.status || ''}"`,
        `"${(issue.remark || '').replace(/"/g, '""')}"`
      ];
      csvData.push(row.join(','));
    });
    
    const csvString = '\ufeff' + csvData.join('\n');
    const blob = new Blob([csvString], { type: 'text/csv;charset=utf-8;' });
    
    const link = document.createElement('a');
    link.href = URL.createObjectURL(blob);
    link.download = `问题管理数据_${new Date().toISOString().slice(0, 10)}.csv`;
    
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    
    showNotification(`成功导出 ${issues.length} 条问题数据到Excel表格`, 'success');
    console.log(`Excel导出完成，共 ${issues.length} 条记录`);
  } catch (error) {
    console.error('导出Excel数据失败:', error);
    showNotification('导出Excel失败', 'error');
  }
};

// 分页操作
const goToPage = (page) => {
  if (page >= 1 && page <= totalPages.value) currentPage.value = page;
};

const getPageNumbers = () => {
  const pages = [];
  const start = Math.max(1, currentPage.value - 2);
  const end = Math.min(totalPages.value, currentPage.value + 2);
  for (let i = start; i <= end; i++) pages.push(i);
  return pages;
};

const handlePageSizeChange = () => { currentPage.value = 1; };

// 标题编辑
const titleManager = {
  load: () => {
    try {
      const savedTitle = localStorageManager.load('systemTitle', '');
      if (savedTitle && typeof savedTitle === 'string') {
        systemTitle.value = savedTitle;
        console.log('从本地存储加载系统标题:', savedTitle);
      }
    } catch (error) {
      console.error('加载系统标题失败:', error);
    }
  },
  
  save: (title) => {
    if (localStorageManager.save('systemTitle', title)) {
      console.log('系统标题已保存到本地存储:', title);
      return true;
    }
    return false;
  },
  
  startEdit: () => {
    isEditingTitle.value = true;
    editingTitleValue.value = systemTitle.value;
    setTimeout(() => {
      const input = document.querySelector('.title-edit-input');
      if (input) {
        input.focus();
        input.select();
      }
    }, 50);
  },
  
  saveEdit: () => {
    if (editingTitleValue.value.trim()) {
      const newTitle = editingTitleValue.value.trim();
      systemTitle.value = newTitle;
      titleManager.save(newTitle);
      isEditingTitle.value = false;
      showNotification('系统标题已更新', 'success');
    } else {
      showNotification('标题不能为空', 'error');
    }
  },
  
  cancelEdit: () => {
    isEditingTitle.value = false;
    editingTitleValue.value = '';
  }
};

const startTitleEdit = titleManager.startEdit;
const saveTitleEdit = titleManager.saveEdit;
const cancelTitleEdit = titleManager.cancelEdit;

// 数据加载
const loadIssuesFromCache = async () => {
  try {
    const existingIssues = await databaseManager.load();
    if (existingIssues.length > 0) {
      tableData.value = existingIssues;
      console.log(`从数据库加载了 ${existingIssues.length} 个问题`);
    } else {
      console.log('数据库为空，使用示例数据');
    }
  } catch (error) {
    console.error('从数据库加载问题数据失败:', error);
  }
};

// ==================== 生命周期 ====================
onMounted(() => {
  console.log('设备管理系统已加载');
  console.log('本地存储功能已就绪');
  
  // 加载系统标题
  titleManager.load();
  
  // 设置监听器
  watch(() => newIssueForm.responsibleDepartment, (newDepartment, oldDepartment) => {
    if (newDepartment !== oldDepartment && newIssueForm.responsiblePersonId) {
      const currentPerson = personList.value.find(p => p.id === parseInt(newIssueForm.responsiblePersonId));
      if (!currentPerson || currentPerson.department !== newDepartment) {
        newIssueForm.responsiblePersonId = '';
      }
    }
  });

  watch(() => editIssueForm.responsibleDepartment, (newDepartment, oldDepartment) => {
    if (newDepartment !== oldDepartment && editIssueForm.responsiblePersonId) {
      const currentPerson = personList.value.find(p => p.id === parseInt(editIssueForm.responsiblePersonId));
      if (!currentPerson || currentPerson.department !== newDepartment) {
        editIssueForm.responsiblePersonId = '';
      }
    }
  });
  
  // 加载本地数据
  const localDevices = localStorageManager.load('deviceList', []);
  if (localDevices.length > 0) {
    const existingNumbers = deviceList.value.map(d => d.machineNumber);
    const newDevices = localDevices.filter(d => !existingNumbers.includes(d.machineNumber));
    if (newDevices.length > 0) {
      deviceList.value.unshift(...newDevices);
      console.log(`从本地存储加载了 ${newDevices.length} 台设备`);
    }
  }

  const localPersons = localStorageManager.load('personList', []);
  if (localPersons.length > 0) {
    const existingNames = personList.value.map(p => p.name);
    const newPersons = localPersons.filter(p => !existingNames.includes(p.name));
    if (newPersons.length > 0) {
      personList.value.unshift(...newPersons);
      console.log(`从本地存储加载了 ${newPersons.length} 个责任人`);
    }
  }

  // 加载问题数据
  loadIssuesFromCache();
});
</script>

<style scoped>
/* 全局样式 */
* {
  box-sizing: border-box;
}

.table-container {
  width: 100%;
  height: 100vh;
  padding: 20px;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

/* 页面标题区域 */
.header-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 20px;
  background: white;
  border-radius: 10px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.page-title {
  font-size: 1.8rem;
  font-weight: 700;
  color: #2d3748;
  display: flex;
  align-items: center;
  gap: 10px;
  margin: 0;
}

/* 标题编辑功能 */
.editable-title {
  cursor: pointer;
  padding: 6px 12px;
  border-radius: 6px;
  transition: all 0.3s ease;
  position: relative;
  display: flex;
  align-items: center;
  gap: 8px;
}

.editable-title:hover {
  background-color: #f7fafc;
  color: #2b6cb0;
}

.title-edit-icon {
  opacity: 0;
  transition: opacity 0.3s ease;
  font-size: 0.9rem;
  color: #a0aec0;
}

.editable-title:hover .title-edit-icon {
  opacity: 1;
}

.title-edit-container {
  display: flex;
  align-items: center;
  gap: 8px;
}

.title-edit-input {
  font-size: 1.8rem;
  font-weight: 700;
  color: #2d3748;
  background: white;
  border: 2px solid #3182ce;
  border-radius: 6px;
  padding: 6px 12px;
  outline: none;
  min-width: 250px;
  box-shadow: 0 0 0 3px rgba(49, 130, 206, 0.1);
}

.title-edit-input:focus {
  border-color: #2b6cb0;
  box-shadow: 0 0 0 3px rgba(49, 130, 206, 0.2);
}

.title-edit-actions {
  display: flex;
  gap: 4px;
}

.title-edit-btn {
  width: 32px;
  height: 32px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 0.9rem;
  transition: all 0.2s ease;
}

.title-edit-btn.save-btn {
  background-color: #48bb78;
  color: white;
}

.title-edit-btn.save-btn:hover {
  background-color: #38a169;
  transform: scale(1.05);
}

.title-edit-btn.cancel-btn {
  background-color: #f56565;
  color: white;
}

.title-edit-btn.cancel-btn:hover {
  background-color: #e53e3e;
  transform: scale(1.05);
}

.header-actions {
  display: flex;
  gap: 10px;
}

/* 问题管理操作区域 */
.issue-actions-section {
  background: white;
  padding: 16px 20px;
  border-radius: 10px;
  margin-bottom: 20px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  border-left: 4px solid #8b5cf6;
}

.issue-actions {
  display: flex;
  gap: 12px;
  justify-content: flex-start;
}

.action-btn {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 10px 16px;
  border: none;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.2s ease;
}

.device-btn {
  background-color: #3182ce;
  color: white;
}

.device-btn:hover {
  background-color: #2c5282;
  transform: translateY(-1px);
}

.person-btn {
  background-color: #48bb78;
  color: white;
}

.person-btn:hover {
  background-color: #38a169;
  transform: translateY(-1px);
}

.department-btn {
  background-color: #805ad5;
  color: white;
}

.department-btn:hover {
  background-color: #6b46c1;
  transform: translateY(-1px);
}

.issue-btn {
  background-color: #8b5cf6;
  color: white;
}

.issue-btn:hover {
  background-color: #7c3aed;
  transform: translateY(-1px);
}



.export-issue-btn {
  background-color: #06b6d4;
  color: white;
}

.export-issue-btn:hover {
  background-color: #0891b2;
  transform: translateY(-1px);
}







/* 表格样式 */
.table-wrapper {
  flex: 1;
  background: white;
  border-radius: 10px;
  overflow: hidden;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  min-height: 0;
}

.data-table {
  width: 100%;
  border-collapse: collapse;
  font-size: 14px;
}

.data-table thead {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  position: sticky;
  top: 0;
  z-index: 10;
}

.data-table th {
  padding: 15px 10px;
  text-align: left;
  font-weight: 600;
  white-space: nowrap;
}

.data-table tbody {
  background: white;
}

.data-table tr {
  border-bottom: 1px solid #e2e8f0;
}

.data-table tbody tr:hover {
  background-color: #f7fafc;
}

.data-table td {
  padding: 12px 10px;
  vertical-align: middle;
}

/* 列宽设置 */
.col-number { width: 100px; }
.col-datetime { width: 140px; }
.col-machine { width: 100px; }
.col-device { width: 150px; }
.col-description { width: 200px; }
.col-stage { width: 100px; }
.col-solution { width: 180px; }
.col-department { width: 100px; }
.col-person { width: 100px; }
.col-status { width: 100px; }
.col-remark { width: 150px; }
.col-actions { 
  width: 120px; 
  text-align: center;
  vertical-align: middle;
}

.col-actions i {
  margin-right: 4px;
  color: #6b7280;
}

.col-actions .action-buttons {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 6px;
  flex-wrap: nowrap;
}

/* 状态标签样式 */
.status-pending {
  background-color: #fed7d7;
  color: #c53030;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 600;
}

.status-processing {
  background-color: #fbd38d;
  color: #c05621;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 600;
}

.status-completed {
  background-color: #c6f6d5;
  color: #276749;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 600;
}

.status-closed {
  background-color: #e2e8f0;
  color: #4a5568;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 600;
}

/* 操作按钮 */
.action-btn-small {
  padding: 6px 8px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
  transition: all 0.2s ease;
  min-width: 32px;
  height: 32px;
  display: inline-flex;
  align-items: center;
  justify-content: center;
}

.edit-btn {
  background-color: #4299e1;
  color: white;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.edit-btn:hover {
  background-color: #3182ce;
  transform: translateY(-1px);
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.15);
}

.delete-btn {
  background-color: #f56565;
  color: white;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.delete-btn:hover {
  background-color: #e53e3e;
  transform: translateY(-1px);
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.15);
}

/* 响应式操作按钮 */
@media (max-width: 768px) {
  .col-actions {
    width: 80px;
  }
  
  .action-btn-small {
    padding: 4px 6px;
    min-width: 28px;
    height: 28px;
    font-size: 11px;
  }
  
  .col-actions .action-buttons {
    gap: 4px;
  }
}

/* 加载和空数据状态 */
.loading-row,
.empty-row {
  text-align: center;
  padding: 40px;
  color: #718096;
  font-size: 16px;
}

.loading-row i,
.empty-row i {
  margin-right: 10px;
  font-size: 18px;
}

/* 分页区域 */
.pagination-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  background: white;
  border-radius: 10px;
  margin-top: 20px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.pagination-info {
  font-size: 14px;
  color: #4a5568;
}

.pagination-controls {
  display: flex;
  gap: 5px;
  align-items: center;
}

.page-btn {
  padding: 8px 12px;
  border: 1px solid #e2e8f0;
  background: white;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.2s ease;
}

.page-btn:hover:not(:disabled) {
  background-color: #edf2f7;
  border-color: #cbd5e0;
}

.page-btn:disabled {
  background-color: #f7fafc;
  color: #a0aec0;
  cursor: not-allowed;
}

.page-btn.active {
  background-color: #4299e1;
  color: white;
  border-color: #4299e1;
}

.page-numbers {
  display: flex;
  gap: 5px;
}

.page-size-selector {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  color: #4a5568;
}

.page-size-selector select {
  padding: 6px 8px;
  border: 1px solid #e2e8f0;
  border-radius: 4px;
  font-size: 14px;
}

/* 新增问题弹窗样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.6);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  backdrop-filter: blur(4px);
}

.add-modal {
  width: 90%;
  max-width: 800px;
  max-height: 90vh;
  overflow-y: auto;
}

.modal-content {
  background-color: white;
  border-radius: 12px;
  box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1);
  animation: modalSlideIn 0.3s ease-out;
}

@keyframes modalSlideIn {
  from {
    opacity: 0;
    transform: scale(0.9) translateY(-20px);
  }
  to {
    opacity: 1;
    transform: scale(1) translateY(0);
  }
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 24px 0;
  border-bottom: 1px solid #e5e7eb;
  margin-bottom: 20px;
}

.modal-title {
  font-size: 1.5rem;
  font-weight: 700;
  color: #1f2937;
  display: flex;
  align-items: center;
  gap: 8px;
  margin: 0;
}

.close-button {
  background: none;
  border: none;
  font-size: 1.5rem;
  color: #6b7280;
  cursor: pointer;
  padding: 8px;
  border-radius: 6px;
  transition: all 0.2s ease;
}

.close-button:hover {
  background-color: #f3f4f6;
  color: #374151;
}

.modal-body {
  padding: 0 24px 20px;
}

.form-row {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;
  margin-bottom: 16px;
}

.form-group {
  margin-bottom: 16px;
}

.form-label {
  display: block;
  margin-bottom: 6px;
  font-weight: 600;
  color: #374151;
  font-size: 14px;
}

.required {
  color: #ef4444;
}

.form-input,
.form-textarea {
  width: 100%;
  padding: 10px 12px;
  border: 1px solid #d1d5db;
  border-radius: 6px;
  font-size: 14px;
  transition: all 0.2s ease;
  box-sizing: border-box;
}

.form-input:focus,
.form-textarea:focus {
  outline: none;
  border-color: #3b82f6;
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}

.form-textarea {
  resize: vertical;
  min-height: 60px;
  font-family: inherit;
}

.modal-footer {
  display: flex;
  gap: 12px;
  padding: 20px 24px;
  border-top: 1px solid #e5e7eb;
  justify-content: flex-end;
}

.modal-btn {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 10px 20px;
  border: none;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.2s ease;
  min-width: 120px;
  justify-content: center;
}

.modal-btn-primary {
  background-color: #3b82f6;
  color: white;
}

.modal-btn-primary:hover {
  background-color: #2563eb;
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(59, 130, 246, 0.4);
}

.modal-btn-secondary {
  background-color: #6b7280;
  color: white;
}

.modal-btn-secondary:hover {
  background-color: #4b5563;
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(107, 114, 128, 0.4);
}

/* 批量新增设备样式 */
.batch-modal {
  max-width: 1000px;
}

/* 已有设备列表样式 */
.existing-devices-section {
  margin-bottom: 24px;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  overflow: hidden;
}

.section-header {
  background: linear-gradient(135deg, #f8fafc, #e2e8f0);
  padding: 12px 16px;
  cursor: pointer;
  transition: all 0.2s ease;
  border-bottom: 1px solid #e5e7eb;
}

.section-header:hover {
  background: linear-gradient(135deg, #f1f5f9, #d1d5db);
}

.section-title {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #374151;
  display: flex;
  align-items: center;
  gap: 8px;
}

.toggle-icon {
  margin-left: auto;
  font-size: 14px;
  transition: transform 0.2s ease;
}

.existing-devices-list {
  max-height: 300px;
  overflow-y: auto;
  background: white;
}

.existing-devices-header {
  display: grid;
  grid-template-columns: 1fr 1.5fr 1fr 80px;
  gap: 12px;
  padding: 12px 16px;
  background: #f9fafb;
  border-bottom: 1px solid #e5e7eb;
  font-weight: 600;
  font-size: 14px;
  color: #374151;
}

.existing-devices-body {
  min-height: 60px;
}

.no-devices {
  padding: 20px;
  text-align: center;
  color: #9ca3af;
  font-style: italic;
}

.existing-device-row {
  display: grid;
  grid-template-columns: 1fr 1.5fr 1fr 80px;
  gap: 12px;
  padding: 10px 16px;
  border-bottom: 1px solid #f3f4f6;
  transition: background-color 0.2s ease;
}

.existing-device-row:hover {
  background-color: #f8fafc;
}

.existing-device-row:last-child {
  border-bottom: none;
}

.device-number {
  font-family: 'Consolas', 'Monaco', monospace;
  font-weight: 600;
  color: #1f2937;
  font-size: 14px;
}

.device-name {
  color: #374151;
  font-size: 14px;
}

.device-time {
  color: #6b7280;
  font-size: 12px;
  font-family: 'Consolas', 'Monaco', monospace;
}

.device-action {
  display: flex;
  justify-content: center;
  align-items: center;
}

.delete-btn {
  background-color: #ef4444;
  color: white;
  border: none;
  border-radius: 4px;
  padding: 6px 8px;
  cursor: pointer;
  font-size: 12px;
  transition: all 0.2s ease;
  display: flex;
  align-items: center;
  justify-content: center;
}

.delete-btn:hover {
  background-color: #dc2626;
  transform: translateY(-1px);
  box-shadow: 0 2px 6px rgba(220, 38, 38, 0.3);
}

/* 已有设备列表滚动条 */
.existing-devices-list::-webkit-scrollbar {
  width: 6px;
}

.existing-devices-list::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.existing-devices-list::-webkit-scrollbar-thumb {
  background: #cbd5e0;
  border-radius: 3px;
}

.existing-devices-list::-webkit-scrollbar-thumb:hover {
  background: #a0aec0;
}

.batch-form-container {
  width: 100%;
}

.batch-header {
  display: grid;
  grid-template-columns: 1fr 1fr 80px;
  gap: 12px;
  padding: 12px 0;
  border-bottom: 2px solid #e5e7eb;
  margin-bottom: 16px;
}

/* 责任人批量新增 - 三列等宽布局 */
.batch-header-person {
  grid-template-columns: 1fr 1fr 1fr 80px;
}

.batch-header-item,
.batch-header-action {
  font-weight: 700;
  color: #374151;
  font-size: 14px;
  display: flex;
  align-items: center;
}

.batch-header-action {
  justify-content: center;
}

.batch-rows {
  max-height: 400px;
  overflow-y: auto;
  margin-bottom: 16px;
}

.batch-row {
  display: grid;
  grid-template-columns: 1fr 1fr 80px;
  gap: 12px;
  padding: 8px 0;
  border-bottom: 1px solid #f3f4f6;
  align-items: center;
}

/* 责任人批量新增行 - 三列等宽布局 */
.batch-row-person {
  grid-template-columns: 1fr 1fr 1fr 80px;
}

.batch-row:hover {
  background-color: #f9fafb;
}

.batch-row-item {
  display: flex;
  align-items: center;
}

.batch-input {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid #d1d5db;
  border-radius: 6px;
  font-size: 14px;
  transition: all 0.2s ease;
}

.batch-input:focus {
  outline: none;
  border-color: #3b82f6;
  box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.1);
}

.batch-row-action {
  display: flex;
  justify-content: center;
}

.batch-btn {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 8px 12px;
  border: none;
  border-radius: 6px;
  font-size: 12px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.2s ease;
}

.batch-btn-add {
  background-color: #10b981;
  color: white;
}

.batch-btn-add:hover {
  background-color: #059669;
  transform: translateY(-1px);
}

.batch-btn-remove {
  background-color: #ef4444;
  color: white;
  padding: 6px 8px;
}

.batch-btn-remove:hover:not(:disabled) {
  background-color: #dc2626;
  transform: translateY(-1px);
}

.batch-btn-remove:disabled {
  background-color: #d1d5db;
  color: #9ca3af;
  cursor: not-allowed;
  transform: none;
}

.batch-actions {
  display: flex;
  justify-content: flex-start;
  padding: 16px 0;
  border-top: 1px solid #e5e7eb;
}

/* 滚动条样式 */
.batch-rows::-webkit-scrollbar {
  width: 6px;
}

.batch-rows::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.batch-rows::-webkit-scrollbar-thumb {
  background: #3b82f6;
  border-radius: 3px;
}

.batch-rows::-webkit-scrollbar-thumb:hover {
  background: #2563eb;
}

/* 响应式设计 - 弹窗 */
@media (max-width: 768px) {
  .add-modal {
    width: 95%;
    max-height: 95vh;
  }

  .batch-modal {
    max-width: 95vw;
  }

  .existing-devices-header,
  .existing-device-row {
    grid-template-columns: 1fr;
    gap: 6px;
    padding: 8px 12px;
  }

  .existing-devices-header span {
    font-size: 12px;
    display: none; /* 在手机端隐藏标题，只显示数据 */
  }

  .existing-device-row {
    flex-direction: column;
    align-items: flex-start;
    border-left: 3px solid #3b82f6;
    background: #f8fafc;
    position: relative;
  }

  .device-number::before {
    content: '编号: ';
    font-weight: 500;
    color: #6b7280;
  }

  .device-name::before {
    content: '名称: ';
    font-weight: 500;
    color: #6b7280;
  }

  .device-time::before {
    content: '时间: ';
    font-weight: 500;
    color: #6b7280;
  }

  .device-action {
    position: absolute;
    top: 8px;
    right: 8px;
  }

  .delete-btn {
    padding: 4px 6px;
    font-size: 10px;
  }

  .batch-header,
  .batch-row,
  .batch-header-person,
  .batch-row-person {
    grid-template-columns: 1fr;
    gap: 8px;
  }

  .batch-header-action,
  .batch-row-action {
    justify-content: flex-start;
  }

  .batch-btn {
    font-size: 14px;
    padding: 10px 16px;
  }

  .form-row {
    grid-template-columns: 1fr;
    gap: 12px;
  }

  .modal-header {
    padding: 16px 20px 0;
  }

  .modal-body {
    padding: 0 20px 16px;
  }

  .modal-footer {
    padding: 16px 20px;
    flex-direction: column;
  }

  .modal-btn {
    width: 100%;
  }
}

/* 通知组件 */
.notification-dialog {
  position: fixed;
  top: 20px;
  left: 50%;
  transform: translateX(-50%);
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 10px 25px rgba(0, 0, 0, 0.15);
  padding: 16px 20px;
  border-left: 4px solid #48bb78;
  width: auto;
  max-width: 400px;
  z-index: 9999;
  opacity: 0;
  visibility: hidden;
  transition: all 0.3s ease;
}

.notification-dialog.show {
  opacity: 1;
  visibility: visible;
}

.notification-dialog.notification-error {
  border-left-color: #f56565;
}

.notification-content {
  display: flex;
  align-items: center;
  gap: 12px;
}

.notification-icon {
  font-size: 18px;
}

.notification-success .notification-icon {
  color: #48bb78;
}

.notification-error .notification-icon {
  color: #f56565;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .table-wrapper {
    overflow-x: auto;
  }
  
  .data-table {
    min-width: 1200px;
  }
}

@media (max-width: 768px) {
  .table-container {
    padding: 10px;
  }
  
  .header-section {
    flex-direction: column;
    gap: 15px;
    text-align: center;
  }
  
  .header-actions {
    justify-content: center;
    flex-wrap: wrap;
  }
  
  .issue-actions {
    justify-content: center;
    flex-wrap: wrap;
  }
  
  /* 响应式标题编辑 */
  .title-edit-input {
    font-size: 1.4rem;
    min-width: 200px;
  }
  
  .title-edit-container {
    flex-direction: column;
    gap: 8px;
    align-items: stretch;
  }
  
  .title-edit-actions {
    justify-content: center;
  }
  

  
  .pagination-section {
    flex-direction: column;
    gap: 15px;
  }
  
  .pagination-controls {
    flex-wrap: wrap;
    justify-content: center;
  }
}

@media (max-width: 480px) {
  .page-title {
    font-size: 1.4rem;
  }
  
  .action-btn {
    padding: 8px 12px;
    font-size: 13px;
  }
  
  .data-table th,
  .data-table td {
    padding: 8px 6px;
    font-size: 12px;
  }
}

/* 新增问题弹窗样式 */
.issue-modal {
  max-width: 600px;
  width: 90%;
}

.issue-modal .form-textarea {
  min-height: 80px;
  resize: vertical;
}

.issue-modal .form-group {
  margin-bottom: 16px;
}

.issue-modal .required {
  color: #e53e3e;
  font-weight: bold;
}

.issue-modal input[type="datetime-local"] {
  padding: 8px 12px;
  border: 1px solid #d1d5db;
  border-radius: 6px;
  font-size: 14px;
  transition: border-color 0.2s ease;
}

.issue-modal input[type="datetime-local"]:focus {
  outline: none;
  border-color: #3b82f6;
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}
</style>

